package com.wang.web3.data.service;

import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.wang.web3.base.Constant;
import com.wang.web3.data.api.Api;
import com.wang.web3.data.api.DeserializerData;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Subscriber;

/**
 * @author Mr.Wang
 * @version 1.0
 * @time 2016/8/22-13:17
 * @describe
 */
public class HttpDao {

    private static final String TAG = HttpDao.class.getSimpleName();
    private static HttpDao mHttpDao = null;

    private HttpDao() {
    };

    public static HttpDao getInstance() {
        if (mHttpDao == null) {
            mHttpDao = new HttpDao();
        }
        return mHttpDao;
    }

    HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
        @Override
        public void log(String message) {
            //打印retrofit日志
            Log.i("RetrofitLog", "retrofitBack = " + message);
        }
    });

    /**
     * 获取 IServiceAPI实列
     *
     * @return IServiceAPI
     */
    public Api getIServiceAPI() {

        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        //retrofit底层用的okHttp,所以设置超时还需要okHttp
        //然后设置5秒超时
        //其中DEFAULT_TIMEOUT是我这边定义的一个常量
        //TimeUnit为java.util.concurrent包下的时间单位
        //TimeUnit.SECONDS这里为秒的单位
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(Constant.DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(Constant.DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(Constant.DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .addInterceptor(loggingInterceptor)
//                .addInterceptor(new Interceptor() {
//                    @Override
//                    public Response intercept(Chain chain) throws IOException {
//                        Request request = chain.request();
//                        Request.Builder builder1 = request.newBuilder();
//                        Request build = builder1.addHeader("Accept", "application/json")
//                                    .addHeader("User-Agent", WebSettings.getDefaultUserAgent(MyApp.getContext().getApplicationContext()));
////                                    .addHeader("Authorization", "Bearer " + UserEntity.getToken()).build();
//                        return chain.proceed(build);
//                    }
//                })
                .build();

        // 使用自定义转换器
        Gson mGson = new GsonBuilder()
                .registerTypeAdapter(String.class, new DeserializerData())
                .create();
        Retrofit mRetrofit = new Retrofit.Builder()
                .baseUrl(Constant.BaseURL)
                .addConverterFactory(GsonConverterFactory.create(mGson))
                //build.gradle引入：compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta4'
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(client)
                .build();
        return mRetrofit.create(Api.class);
    }


    /**
     * 创建 Subscriber
     *
     * @param mICallBackListener
     * @return Subscriber
     */
    public Subscriber createSubscriber(final ICallBackListener mICallBackListener) {
        Subscriber mSubscriber = new Subscriber<String>() {
            @Override
            public void onCompleted() {
                Log.i(TAG, "[onCompleted]");
            }

            @Override
            public void onError(Throwable e) {
                Log.e(TAG, "[onError]" + e.getMessage());
                CallBackVo mCallBackVo = new CallBackVo();
                mCallBackVo.setCode(1);
                mCallBackVo.setMessage("请求失败");
                mCallBackVo.setError("请求失败");
                mCallBackVo.setResult(null);
                mICallBackListener.onFaild("失败");
                return;
            }

            @Override
            public void onNext(String s) {
                Log.i(TAG, "[onNext]" + s);
                Gson gson = new Gson();
                CallBackVo callBackVo = gson.fromJson(s,CallBackVo.class);
                if(callBackVo.getCode() == 0){
                    mICallBackListener.onSuccess(s);
                }else{
                    mICallBackListener.onFaild(s);
                }
            }
        };
        return mSubscriber;
    }

}
